﻿using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using Library.Util;

namespace Library.Cloud.Util
{
    public class PortletUtil
    {
        public static DataTable RssReader(string url)
        {
            XmlTextReader reader = null;
            var ds = new DataSet();
            try
            {
                reader = new XmlTextReader(url);
                ds.ReadXml(reader);
                return ds.Tables["item"];
            }
            catch (Exception ex)
            {
                var dt = new DataTable("item");
                dt.Columns.Add("title", typeof (string));
                dt.Columns.Add("description", typeof (string));
                dt.Columns.Add("pubDate", typeof (string));
                dt.Columns.Add("image", typeof (string));
                dt.Columns.Add("item_Id", typeof (string));
                dt.Columns.Add("link", typeof (string));
                dt.Columns.Add("guid", typeof (string));
                dt.Columns.Add("channel_Id", typeof (string));

                dt.Rows.Add(new[]
                                {
                                    "Hata Oluştu", ExceptionUtil.ParseExceptions(ex), DateTime.Now.ToShortDateString(),
                                    "/Images/Common/Error.gif", "1", "", "", ""
                                });
                return dt;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                ds.Dispose();
            }
        }

        public static string TwitterReader(string userName, int count = 10)
        {
            XmlTextReader reader = null;
            try
            {
                reader = new XmlTextReader("http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=" + userName);
                var myxml = new XmlDocument();
                myxml.Load(reader);

                var nodes = myxml.SelectNodes("rss/channel/item/description");
                if (nodes == null)
                    return "Akış bulunamadı.";

                var RFC822 = "ddd, dd MMM yyyy HH:mm:ss zzz"; 
                var sb = new StringBuilder();
                for (var i = 0; i < count; i++)
                {
                    if (nodes[i] == null) break;
                    var dt = DateTime.ParseExact(myxml.SelectNodes("rss/channel/item/pubDate")[i].InnerText, RFC822, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);
                    sb.Append("<span class=\"PubDate\">");
                    sb.Append(userName + " " + dt.ToShortDateString() + " " + dt.ToShortTimeString() + " tarihinde dedi ki;<br />");
                    sb.Append("</span>");
                    sb.Append(nodes[i].InnerText);
                    sb.Append("<br/>");
                    sb.Append("<br/>");
                }
                
                return sb.ToString().Replace(userName + ":", "");

                //return myxml.SelectSingleNode("rss/channel/item/description").InnerText.Replace(userName + ":", "");
            } catch(Exception ex)
            {
                return ExceptionUtil.ParseExceptions(ex);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }

        public static string HavaDurumu(string il)
        {
            try
            {
                const string template = @"
                <table cellpadding=""0"" cellspacing=""0"" border=""0"" class=""Weather"">
                    <tr>
                        <td style=""vertical-align:top; text-align:left;""><img width=""90px"" src=""{0}"" alt="""" /></span></td>
                        <td style=""vertical-align:top"">
                            <table cellpadding=""0"" cellspacing=""0"" border=""0"" style=""text-align:left;"">
                                <tr>
                                    <td><span class=""Derece"">{1}</span></td>
                                </tr>
                                <tr>
                                    <td><span class=""Durum"">{2}</span></td>
                                </tr>
                                <tr>
                                    <td><span class=""Nem"">{3}</span></td>
                                </tr>
                                <tr>
                                    <td><span class=""Ruzgar"">{4}</span></td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr>
                        <td colspan=""2"">
                            <table cellpadding=""0"" cellspacing=""0"" border=""0"" width=""100%"">
                                <tr>
                                    <td><span class=""NextDayName"">{5}</span></td>
                                    <td><span class=""NextDayName"">{6}</span></td>
                                    <td><span class=""NextDayName"">{7}</span></td>
                                    <td><span class=""NextDayName"">{20}</span></td>
                                </tr>
                                <tr>
                                    <td><img width=""75"" src=""{8}"" class=""TipTip"" title=""{17}""/></td>
                                    <td><img width=""75"" src=""{9}"" class=""TipTip"" title=""{18}""/></td>
                                    <td><img width=""75"" src=""{10}"" class=""TipTip"" title=""{19}""/></td>
                                    <td><img width=""75"" src=""{21}"" class=""TipTip"" title=""{22}""/></td>
                                </tr>
                                <tr>
                                    <td><span class=""DayDeg"" >{11}</span><span class=""NightDeg"" >{12}</span></td>
                                    <td><span class=""DayDeg"" >{13}</span><span class=""NightDeg"" >{14}</span></td>
                                    <td><span class=""DayDeg"" >{15}</span><span class=""NightDeg"" >{16}</span></td>
                                    <td><span class=""DayDeg"" >{23}</span><span class=""NightDeg"" >{24}</span></td>
                                </tr>
                            </table>
                        </td>
                    </tr>                    
                </table>
";

                var strGelenIl = il;
                if (string.IsNullOrEmpty(strGelenIl))
                    strGelenIl = "ANKARA";

                var webClient = new WebClient();
                var strKaynak = webClient.DownloadString("http://www.google.com/ig/api?weather=" + strGelenIl + "&hl=tr");
                var trOkuyucu = new StringReader(strKaynak);
                webClient.Dispose();

                var rdr = new XmlTextReader(trOkuyucu);
                var myxml = new XmlDocument();
                myxml.Load(rdr);
                var xnlHedef = myxml.SelectNodes("xml_api_reply/weather/current_conditions");
                if (xnlHedef == null)
                    throw new NullReferenceException("Hava durumu bilgisi alınamadı.");
                if (xnlHedef.Item(0) == null)
                    throw new NullReferenceException("Hava durumu bilgisi alınamadı.");
                
                // ReSharper disable PossibleNullReferenceException
                var icon = xnlHedef.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText;
                var dayIcon = "/Images/Weather/" + icon.Substring(icon.LastIndexOf('/') + 1).Replace(".gif", ".png");

                var strDerece = xnlHedef.Item(0).SelectSingleNode("temp_c").Attributes["data"].InnerText + " °C";
                var strDurum = xnlHedef.Item(0).SelectSingleNode("condition").Attributes["data"].InnerText;
                var strNem = xnlHedef.Item(0).SelectSingleNode("humidity").Attributes["data"].InnerText;
                var strRuzgar = xnlHedef.Item(0).SelectSingleNode("wind_condition").Attributes["data"].InnerText;

                xnlHedef = myxml.SelectNodes("xml_api_reply/weather/forecast_conditions");
                var next1Day = xnlHedef.Item(0).SelectSingleNode("day_of_week").Attributes["data"].InnerText;
                var next2Day = xnlHedef.Item(1).SelectSingleNode("day_of_week").Attributes["data"].InnerText;
                var next3Day = xnlHedef.Item(2).SelectSingleNode("day_of_week").Attributes["data"].InnerText;
                var next4Day = xnlHedef.Item(3).SelectSingleNode("day_of_week").Attributes["data"].InnerText;

                icon = xnlHedef.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText;

                var next1Image = "/Images/Weather/" + icon.Substring(icon.LastIndexOf('/') + 1).Replace(".gif", ".png");
                icon = xnlHedef.Item(1).SelectSingleNode("icon").Attributes["data"].InnerText;
                var next2Image = "/Images/Weather/" + icon.Substring(icon.LastIndexOf('/') + 1).Replace(".gif", ".png");
                icon = xnlHedef.Item(2).SelectSingleNode("icon").Attributes["data"].InnerText;
                var next3Image = "/Images/Weather/" + icon.Substring(icon.LastIndexOf('/') + 1).Replace(".gif", ".png");
                icon = xnlHedef.Item(3).SelectSingleNode("icon").Attributes["data"].InnerText;
                var next4Image = "/Images/Weather/" + icon.Substring(icon.LastIndexOf('/') + 1).Replace(".gif", ".png");

                var next1DayDeg = xnlHedef.Item(0).SelectSingleNode("high").Attributes["data"].InnerText + "°C ";
                var next2DayDeg = xnlHedef.Item(1).SelectSingleNode("high").Attributes["data"].InnerText + "°C ";
                var next3DayDeg = xnlHedef.Item(2).SelectSingleNode("high").Attributes["data"].InnerText + "°C ";
                var next4DayDeg = xnlHedef.Item(3).SelectSingleNode("high").Attributes["data"].InnerText + "°C ";

                var next1NightDeg = xnlHedef.Item(0).SelectSingleNode("low").Attributes["data"].InnerText + "°C";
                var next2NightDeg = xnlHedef.Item(1).SelectSingleNode("low").Attributes["data"].InnerText + "°C";
                var next3NightDeg = xnlHedef.Item(2).SelectSingleNode("low").Attributes["data"].InnerText + "°C";
                var next4NightDeg = xnlHedef.Item(3).SelectSingleNode("low").Attributes["data"].InnerText + "°C";

                var next1Comment = xnlHedef.Item(0).SelectSingleNode("condition").Attributes["data"].InnerText;
                var next2Comment = xnlHedef.Item(1).SelectSingleNode("condition").Attributes["data"].InnerText;
                var next3Comment = xnlHedef.Item(2).SelectSingleNode("condition").Attributes["data"].InnerText;
                var next4Comment = xnlHedef.Item(3).SelectSingleNode("condition").Attributes["data"].InnerText;
                // ReSharper restore PossibleNullReferenceException

                trOkuyucu.Dispose();
                rdr.Close();

                var param = new object[25];
                param[0] = dayIcon;
                param[1] = strDerece;
                param[2] = strDurum;
                param[3] = strNem;
                param[4] = strRuzgar;
                param[5] = "Bugün";
                param[6] = "Yarın";
                param[7] = DayNameConverter(next3Day);
                param[8] = next1Image;
                param[9] = next2Image;
                param[10] = next3Image;
                param[11] = next1DayDeg;
                param[12] = next1NightDeg;
                param[13] = next2DayDeg;
                param[14] = next2NightDeg;
                param[15] = next3DayDeg;
                param[16] = next3NightDeg;
                param[17] = next1Comment;
                param[18] = next2Comment;
                param[19] = next3Comment;
                param[20] = DayNameConverter(next4Day);
                param[21] = next4Image;
                param[22] = next4Comment;
                param[23] = next4DayDeg;
                param[24] = next4NightDeg;

                return String.Format(template, param);
            }
            catch (Exception ex)
            {
                return ExceptionUtil.ParseExceptions(ex);
            }
        }

        private static string DayNameConverter(string dayName)
        {
            switch (dayName)
            {
                case "Sal":
                    return "Salı";
                case "Çar":
                    return "Çarşamba";
                case "Per":
                    return "Perşembe";
                case "Cum":
                    return "Cuma";
                default:
                    return dayName;
            }
        }
    }
}
